import { LogLevel } from '@gnlab/utils'
import { Switch, Select, App } from 'antd'
import { getFlags, setFlags } from '@/lib/logging-flags'

export function Logging() {
  const { message } = App.useApp()
  const [flags, setFlagsState] = useState(() => getFlags())

  function setLogLevel(level: LogLevel) {
    const newFlags = { ...flags, level }
    setFlags(newFlags)
    setFlagsState(newFlags)
    void message.success('日志配置已修改')
  }

  function switchThirdParty() {
    const newFlags = { ...flags, thirdParty: flags.thirdParty ? '' : '*' }
    setFlags(newFlags)
    setFlagsState(newFlags)
    void message.success('日志配置已修改')
  }

  const levelOptions = useMemo(
    () => [
      { label: 'debug', value: LogLevel.Debug },
      { label: 'info', value: LogLevel.Info },
      { label: 'warning', value: LogLevel.Warning },
      { label: 'error', value: LogLevel.Error },
    ],
    [],
  )

  return <>
    <h5>日志</h5>
    <div css={styles.field}>
      <label className="settings-label">日志级别：</label>
      <Select options={levelOptions} value={flags.level} onChange={setLogLevel} />
    </div>
    <div css={styles.field}>
      <label className="settings-label">记录三方库：</label>
      <Switch
        checked={!!flags.thirdParty}
        onClick={switchThirdParty}
        checkedChildren="开启"
        unCheckedChildren="关闭"
      />
    </div>
  </>
}

const styles = {
  field: css`
    align-items: center;
    display: flex;
    margin-bottom: 24px;
    label {
      width: 6em;
    }
    .ant-select {
      width: 7em;
    }
  `,
}
